package com.ms.p2p.controller.admin;


import com.alibaba.dubbo.config.annotation.Reference;
import com.ms.common.bean.Message;
import com.ms.common.exception.NoticeException;
import com.ms.p2p.bean.PageBean;
import com.ms.p2p.controller.BaseController;
import com.ms.p2p.entity.content.ArticleCategory;
import com.ms.p2p.provider.ArticleCategoryProvider;
import com.ms.p2p.provider.ArticleProvider;
import com.ms.p2p.utils.JsonDataGridHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.beans.IntrospectionException;
import java.lang.reflect.InvocationTargetException;
import java.util.List;


/**
 * 文章类型
 */
@Controller("AdminArticleCategoryController")
@RequestMapping({ "/admin/articleCate" })
public class AdminArticleCategoryController extends AdminBaseController {

	@Reference
	private ArticleProvider newsService;
	@Reference
	private ArticleCategoryProvider newsTypeService;

	@RequestMapping({ "/list" })
	public String list(HttpServletRequest request) {

		return "admin/articleCate/list";
	}

	@RequestMapping(value = {"/queryData"})
	@ResponseBody
	public PageBean queryData(HttpServletRequest request, HttpSession session,PageBean page
	) {
		List list = newsTypeService.getlist();

		page.setList(list);
		page.setPageSize(list.size());
		return JsonDataGridHelper.createJSONData(page);
	}

	@RequestMapping({ "/add" })
	public String add(String typeId, Model model) {
		if (StringUtils.isNotBlank(typeId)) {
			model.addAttribute("newsType", newsTypeService.get(typeId));
		}
		return "admin/articleCate/add";
	}


	@RequestMapping("/edit")
	@ResponseBody
	public Message typeadd(HttpServletRequest request, HttpSession session,
						   ArticleCategory newstype) throws IllegalAccessException,
			InvocationTargetException, IntrospectionException {
		String typeId = request.getParameter("typeId");
		if (StringUtils.isBlank(typeId) || "0".equals(typeId)) {
			if (newsTypeService.insert(newstype) > 0) {
				return Message.success("添加成功");
			}
		} else {
			newstype.setId(Integer.parseInt(typeId));
			if (newsTypeService.update(newstype) > 0) {
				return Message.success("修改成功");
			}
		}
		throw new NoticeException("操作失败");
	}


	@RequestMapping("/delete")
	public String delNewsType(HttpServletRequest request, HttpSession session) {
		String typeId = request.getParameter("typeId");
		newsTypeService.del(Integer.parseInt(typeId));
		return "redirect:/admin/articleCate/list.aspx";
	}

	@Override
	public boolean getBinderFlag() {
		return false;
	}
}
